---
title: "Authentication"
description: "mcp-use supports multiple authentication methods for MCP servers, including OAuth 2.0 with automatic Dynamic Client Registration (DCR), bearer tokens, and custom authentication providers."
icon: "key"
tag: "New"
---

## Quick Start

### OAuth Authentication

For servers that support OAuth, you can use Dynamic Client Registration (automatic) or pre-registered clients:

<CodeGroup>
```python Python
from mcp_use import MCPClient, MCPAgent
from langchain_openai import ChatOpenAI

# Dynamic Client Registration (automatic)
config = {
    "mcpServers": {
        "linear": {
            "url": "https://mcp.linear.app/sse",
            # It's not needed to specify auth section
        }
    }
}

# Or with pre-registered client
config = {
    "mcpServers": {
        "my_server": {
            "url": "https://api.example.com/mcp/",
            "auth": {
                "client_id": "your-client-id",
                "client_secret": "your-client-secret",
            }
        }
    }
}

# Create client and agent
client = MCPClient(config=config)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = MCPAgent(llm=llm, client=client)

# Use the agent
response = await agent.run("Your query here")
print(response)
```
</CodeGroup>

### Bearer Token Authentication

For servers requiring API keys:

<CodeGroup>
```python Python
config = {
    "mcpServers": {
        "api": {
            "url": "https://api.example.com/mcp/sse",
            "auth": "sk-your-api-key-here"
        }
    }
}
```
</CodeGroup>

### Custom Port Configuration

You can specify a custom port for OAuth callbacks to avoid conflicts:

<CodeGroup>
```python Python
config = {
    "mcpServers": {
        "my_server": {
            "url": "https://api.example.com/mcp/",
            "auth": {
                "client_id": "your-client-id",
                "client_secret": "your-client-secret",
                "callback_port": 8082,  # Use custom port instead of default 8080
            }
        }
    }
}
```
</CodeGroup>

## Authentication Methods

### 1. OAuth 2.0 Authentication

OAuth 2.0 is the most common authentication method for MCP servers. mcp-use supports:

- **Dynamic Client Registration (DCR)** - Automatic client registration
- **Pre-registered Clients** - Using existing OAuth applications
- **Custom OAuth Providers** - With explicit metadata

#### Dynamic Client Registration

For servers that support DCR, you don't need to register a client manually:

```python
config = {
    "mcpServers": {
        "linear": {
            "url": "https://mcp.linear.app/sse",
            "auth": {
                "scope": "read write"  # Optional scopes
            }
        }
    }
}
```

#### Pre-registered OAuth Client

For servers requiring manual client registration:

```python
config = {
    "mcpServers": {
        "example": {
            "url": "https://api.example.com/mcp/",
            "auth": {
                "client_id": "your-registered-client-id",
                "client_secret": "your-client-secret",  # Optional
                "callback_port": 8081,  # Optional custom port
            }
        }
    }
}
```

#### OAuth Provider with Metadata

For servers with known OAuth endpoints, provide metadata upfront:

```python
config = {
    "mcpServers": {
        "linear": {
            "url": "https://mcp.linear.app/sse",
            "auth": {
                "oauth_provider": {
                    "id": "linear",
                    "display_name": "Linear",
                    "metadata": {
                        "issuer": "https://mcp.linear.app",
                        "authorization_endpoint": "https://mcp.linear.app/authorize",
                        "token_endpoint": "https://mcp.linear.app/token",
                        "registration_endpoint": "https://mcp.linear.app/register"
                    }
                }
            }
        }
    }
}
```

### 2. Bearer Token Authentication

For servers requiring simple API keys or bearer tokens:

```python
config = {
    "mcpServers": {
        "api": {
            "url": "https://api.example.com/mcp/sse",
            "auth": "sk-your-api-key-here"
        }
    }
}
```

### 3. Custom Authentication

For servers requiring custom authentication methods:

```python
from httpx import BasicAuth, DigestAuth

config = {
    "mcpServers": {
        "secure": {
            "url": "https://secure.example.com/mcp/sse",
            "auth": BasicAuth("username", "password")
        },
        "digest": {
            "url": "https://digest.example.com/mcp/sse",
            "auth": DigestAuth("username", "password")
        }
    }
}
```

### 4. No Authentication

For public servers or servers without authentication:

```python
config = {
    "mcpServers": {
        "public": {
            "url": "https://public.example.com/mcp/sse"
            # No auth config - will attempt discovery or continue without auth
        }
    }
}
```

## Complete Examples

### GitHub MCP Server Example

The GitHub MCP server requires OAuth authentication. You'll need to create a GitHub OAuth App first:

1. **Create a GitHub OAuth App**:
   - Go to [GitHub OAuth Apps](https://github.com/settings/applications/new)
   - Set **Application name**: `your-app-name`
   - Set **Homepage URL**: `http://localhost:8080` (or your custom port)
   - Set **Authorization callback URL**: `http://localhost:8080/callback` (or your custom port)
   - Click "Register application"
   - Copy your **Client ID** and **Client Secret**

2. **Configure mcp-use**:

```python
import asyncio
from mcp_use import MCPClient, MCPAgent
from langchain_openai import ChatOpenAIxw

async def github_example():
    # GitHub MCP server configuration
    config = {
        "mcpServers": {
            "github": {
                "url": "https://api.githubcopilot.com/mcp/",
                "auth": {
                    "client_id": "your-github-client-id",
                    "client_secret": "your-github-client-secret",
                    "scope": "repo", # Needed for GitHub
                    "callback_port": 8080,  # The same port as the callback on OAuth app
                }
            }
        }
    }

    # Create client and agent
    client = MCPClient(config=config)
    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    agent = MCPAgent(llm=llm, client=client, max_steps=30)

    # Example queries
    queries = [
        "Your queries"
    ]

    for query in queries:
        print(f"\n🔍 Query: {query}")
        response = await agent.run(query)
        print(f"📝 Response: {response}")

if __name__ == "__main__":
    asyncio.run(github_example())
```

### Multi-Server Configuration

You can mix different authentication methods across servers:

```python
from httpx import BasicAuth

config = {
    "mcpServers": {
        "github": {
            "url": "https://api.githubcopilot.com/mcp/",
            "auth": {
                "client_id": "your-github-client-id",
                "client_secret": "your-github-client-secret",
                "scope": "repo",
                "callback_port": 8082, # Remember to use the same on GitHub
            }
        },
        "linear": {
            "url": "https://mcp.linear.app/sse",
            # DCR
        },
        "api": {
            "url": "https://api.example.com/mcp/sse",
            "auth": "sk-api-key" # Bearer token
        },
        "secure": {
            "url": "https://secure.example.com/mcp/sse",
            "auth": BasicAuth("username", "password") # Custom auth
        }
    }
}

client = MCPClient(config=config)
```

## OAuth Flow Process

When OAuth authentication is required:

1. **Browser Opens**: Your default browser opens to the authorization page
2. **Grant Access**: Review and approve the requested permissions
3. **Automatic Redirect**: You're redirected to a local callback URL
4. **Token Storage**: Access tokens are stored securely in `~/.mcp_use/tokens/`

## Token Storage

Authentication data is stored securely:
- **Access Tokens**: `~/.mcp_use/tokens/{server_domain}.json`
- **Client Registrations**: `~/.mcp_use/tokens/registrations/{server_domain}_registration.json`

## Configuration Options

### OAuth Configuration Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `client_id` | string | No* | OAuth client ID (required if not using DCR) |
| `client_secret` | string | No | OAuth client secret (required if not using DCR) |
| `scope` | string | No | OAuth scopes to request |
| `callback_port` | integer | No | Port for OAuth callback (default: 8080) |
| `oauth_provider` | object | No | OAuth provider metadata |

*Required unless using Dynamic Client Registration

### Port Configuration

- **Default Port**: 8080
- **Custom Ports**: Any available port (e.g., 8081, 8082, 3000)
- **Port Conflicts**: mcp-use will check if the port is available before starting OAuth flow

## Troubleshooting

### Common Issues

#### OAuth Discovery Fails

If a server doesn't support OAuth discovery:
- Provide an `oauth_provider` with metadata
- Use a pre-registered `client_id`
- Check if the server requires different authentication

#### "Invalid redirect URI" Error

Solutions:
- Use Dynamic Client Registration (omit `client_id`)
- Register your app with supported redirect URIs
- Check if your provider supports wildcard redirect URIs
- Ensure callback URL matches your OAuth app configuration

#### Port Already in Use

If you get a port conflict error:
```python
# Use a different port
"callback_port": 8081  # or any other available port
```

#### GitHub OAuth Issues

For GitHub specifically:
- Ensure your OAuth app callback URL matches: `http://localhost:8080/callback` (or your custom port)
- Use correct scopes: `repo`, `read:user`, etc.
- Check that your GitHub OAuth app is properly configured

### Debugging

Enable debug logging to see detailed authentication flow:

```python
from mcp_use import set_debug
set_debug(2)  # Enable verbose logging
```

## Security Best Practices

- **Token Storage**: Tokens are stored with restricted permissions
- **Version Control**: Never commit authentication files to version control
- **CSRF Protection**: OAuth flow uses state parameter for CSRF protection
- **Localhost Callbacks**: All callbacks use localhost (127.0.0.1) for security
- **Isolation**: Each server's authentication is isolated
- **Environment Variables**: Use environment variables for sensitive data:

```python
import os

config = {
    "mcpServers": {
        "github": {
            "url": "https://api.githubcopilot.com/mcp/",
            "auth": {
                "client_id": os.getenv("GITHUB_CLIENT_ID"),
                "client_secret": os.getenv("GITHUB_CLIENT_SECRET"),
                "scope": "repo",
            }
        }
    }
}
```

## Example Servers that support OAuth

### OAuth with DCR Support
- **Linear**: `https://mcp.linear.app/sse`
- **Asana**: `https://mcp.asana.com/sse`
- **Atlassian**: `https://mcp.atlassian.com/v1/sse`

### OAuth with Manual Registration
- **GitHub**: `https://api.githubcopilot.com/mcp/`

### Bearer Token
- Most API-based MCP servers

Check your server's documentation for specific authentication requirements and supported methods.
